﻿using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.Win32;

namespace TgaScanner
{
    internal class MainWindowViewModel : INotifyPropertyChanged
    {
        public MainWindowViewModel()
        {
            SelectedDirectory = "E:\\SGameProj\\Project\\Assets\\Art_Resources\\Shared\\Characters\\Hero";
            FileItems = new ObservableCollection<FileItem>();
            StatusText = "请选择你要扫描的目录。";
        }

        private string selectedDirectory;

        public string SelectedDirectory
        {
            get
            {
                return selectedDirectory;
            }
            set
            {
                selectedDirectory = value;
                OnPropertyChanged();
            }
        }

        public void SelectDirectory()
        {
            using (var folderDialog = new System.Windows.Forms.FolderBrowserDialog())
            {
                System.Windows.Forms.DialogResult result = folderDialog.ShowDialog();
                if (result == System.Windows.Forms.DialogResult.OK &&
                    !string.IsNullOrWhiteSpace(folderDialog.SelectedPath))
                {
                    SelectedDirectory = folderDialog.SelectedPath;
                }
            }
        }

        private ObservableCollection<FileItem> fileItems;

        public ObservableCollection<FileItem> FileItems
        {
            get { return fileItems; }
            set
            {
                fileItems = value;
                OnPropertyChanged();
            }
        }

        public async void ScanDirectory()
        {
            if (string.IsNullOrEmpty(selectedDirectory) || !Directory.Exists(selectedDirectory))
            {
                return;
            }

            StatusText = $"正在扫描，请耐心等待……";

            await Task.Run(() =>
            {
                var tgaFiles = Directory.GetFiles(selectedDirectory, "*.tga", SearchOption.AllDirectories);

                // 更新 UI 线程中的 ObservableCollection
                Application.Current.Dispatcher.Invoke(() =>
                {
                    StatusText = $"扫描到 {tgaFiles.Length} 个文件，正在分析……";
                });

                var fileItems = new ObservableCollection<FileItem>();
                int count = 0;

                foreach (var tgaFile in tgaFiles)
                {
                    string filepath = Path.GetFullPath(tgaFile);
                    int width = 0;
                    int height = 0;
                    int channels = 0;
                    using (var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
                    {
                        using (var binaryReader = new BinaryReader(fileStream))
                        {
                            binaryReader.ReadBytes(12);
                            width = binaryReader.ReadUInt16();
                            height = binaryReader.ReadUInt16();
                            channels = binaryReader.ReadByte() / 8;
                        }
                    }

                    fileItems.Add(new FileItem
                    {
                        FileName = filepath,
                        Width = width,
                        Height = height,
                        Channels = channels
                    });

                    if (++count % 100 == 0)
                    {
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            StatusText = $"分析进行中，当前进度：{count} / {tgaFiles.Length}。";
                        });
                    }
                }

                Application.Current.Dispatcher.Invoke(() =>
                {
                    FileItems.Clear();

                    foreach (var fileItem in fileItems)
                    {
                        FileItems.Add(fileItem);
                    }
                });
            });

            StatusText = $"扫描完成，总的文件数目为：{FileItems.Count}";
        }

        public void ExportFileItems()
        {
            if (FileItems.Count == 0)
            {
                return;
            }

            var saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Text Files | *.txt";

            if (saveFileDialog.ShowDialog() == true)
            {
                using (var streamWriter = new StreamWriter(saveFileDialog.FileName))
                {
                    foreach (var fileItem in FileItems)
                    {
                        streamWriter.WriteLine($"{fileItem.FileName}, {fileItem.Width},{fileItem.Height},{fileItem.Channels}");
                    }
                }

                StatusText = $"导出完成，导出文件为：{saveFileDialog.FileName}";
            }
        }

        private string statusText;

        public string StatusText
        {
            get { return statusText; }
            set
            {
                statusText = value;
                OnPropertyChanged();
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
